package com.mef.smsplat.eterm;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.hc24.util.DateUtil;
import com.mef.smsplat.eterm.bean.PNRPasseenger;
import com.mef.smsplat.eterm.bean.PNRSeg;
import com.mef.smsplat.eterm.bean.PNRTicket;
import com.mef.smsplat.eterm.bean.RtResult;

public final class RtUtil {
	public static RtResult parseRt(String content, String pnr) {

		String[] items = initArgs(content);
		if (items == null) {
			return null;
		}
		RtResult result = new RtResult();
		result.setPnrCode(pnr);

		initGrop(items, result);
		int pnrIndex = -1;
		if(!result.isGroup()){
			for (int i = 0; i < items.length; i++) {
				if (items[i].indexOf(pnr) > -1) {
					pnrIndex = i + 1;
					break;
				}
			}
			if (pnrIndex == -1)
				return result;
		}
		
		getPassenger(result, items, pnrIndex);
		for (String temp : items) {
			getChild(result,temp);
		}
		for (String temp : items) {
			getFOID4Passenger(result, temp);
			getTKT(result, temp);
			getSeg(result,temp);
			getPhoneNumber(result, temp) ;
		}
		result.setOfficeCode(getOfficeCode(items[items.length-1]));
		return result;
	}

	private static void getPhoneNumber(RtResult result, String temp) {
		//手机号码只取OSI的CTCT项
		if(temp.indexOf("CTCT")==-1)
			return;
		getPhone(temp, result.getPhoneList());
		
	}

	private static void getChild(RtResult result, String string) {
		
		if (string.indexOf("SSR INFT") > -1) {//婴儿
			//SSR INFT EU HK1 NNGCTU 2230 Y29SEP LI/MULIN 24DEC10/P1
			String[] arrays = split(string, " ");
			
			boolean flag = false;
			String[] temp = split(arrays[8],"/");
			for(PNRPasseenger ps : result.getPasseengerList()){
				if(PNRPasseenger.PASSENGER_TYPE_INFANT.equals(ps.getType())){
					if(ps.getIdNo().equals(temp[0]) && ps.getName().equals(arrays[7]) )
						flag = true;
				}
			}
			if(flag)
				return;
			PNRPasseenger entity = new PNRPasseenger();
			entity.setType(PNRPasseenger.PASSENGER_TYPE_INFANT);
			entity.setName(arrays[7]);
			entity.setIdNo(temp[0]);
			PNRPasseenger aduit = result.getPasseengerList().get(Integer.parseInt(temp[0].substring(1)));
			entity.setIdNo4Infant(aduit.getIdNo());
			entity.setName4Infant(aduit.getName());
			result.getPasseengerList().add(entity);
			result.setPassengerNumber(result.getPassengerNumber()+1);
		}
	}
	private static void initGrop(String[] items, RtResult result) {
		if(items[0].indexOf("/GRP")>0){
			result.setGroup(true);
			String[] arrays = split(items[0], " ");
			result.setPassengerNumber(Integer.parseInt(arrays[1].substring(2)));
			result.setGroupName(arrays[0].substring(arrays[0].length()-9, arrays[0].length()-4));
			result.setPassengerNumber(result.getPassengerNumber());
		}
	}

	private static void getSeg(RtResult result, String string) {
		String patt = "RR\\d{1,2}";
		Pattern p = Pattern.compile(patt);
		Matcher m = p.matcher(string);
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		String year = format.format(new Date());;
		if (m.find()){
			// 3.  3U8882 Y   FR28SEP  PEKCTU RR2   1120 1415          E T3T1 
			String[] items = split(string, " ");
			PNRSeg seg = null;
			if(items.length>=9){
				seg = new PNRSeg();
				seg.setActionCode("RR");
				seg.setAirNo(items[1]);
				seg.setCabin(items[2]);
				seg.setOrgCity(items[4].substring(0,3));
				seg.setDesCity(items[4].substring(3));
				
				
				if(items[3].substring(2).length()<=6){
					seg.setSegDate(items[3].substring(2)+year);
				}
				seg.setSegDate(DateUtil.ymd(seg.getSegDate()));
				
				seg.setDepartureTime(items[6]);
				seg.setArrivalTime(items[7]);
				if(items.length>=10){
					seg.setDepartureTerm(items[9].substring(0,2));
					seg.setArrivalTerm(items[9].substring(2));
				}
			}
			result.getSegsList().add(seg);
		}
	}

	private static String getOfficeCode(String string) {
		if(string.indexOf("PEK1E")>-1){//cpnr
				return string.substring(string.length()-6);
		}else{//bpnr
			String patt = "\\d{1,3}\\.";
			Pattern p = Pattern.compile(patt);
			Matcher m = p.matcher(string);
			if (m.find()){
				//12.PEK777
				//12.PEK777		-13.PEK888
				String temp[] = split(string, "\\.");
				return temp[temp.length-1];
			}else{
				return string.substring(2);
			}
		}
	}
	private static void getPhone(String arg,List<String> phoneList){
		//String[] patts = {"\\d{3,4}-\\d{7,8}", "\\d{7,8}","1[358]\\d{9}"};
		String[] patts={"\\d{11}"};
		for(String patt:patts ){
			Pattern p = Pattern.compile(patt);
			Matcher m = p.matcher(arg);
			if (m.find()){
				int j = m.groupCount();
				for(int k=0;k<=j;k++){
					boolean flag = false;
					String phone =  m.group(j);
					for(String temp : phoneList){
						if(temp.indexOf(phone)>-1){
							flag = true;
							break;
						}
					}
					if(!flag)
						phoneList.add(m.group(j));
				}
			}
		}
		
	}

	private static String[] initArgs(String str) {
		if (StringUtils.isEmpty(str)) {
			return null;
		}
		str = str.trim();
		if (str.indexOf("NO PNR") > -1 || str.indexOf("NO NAME LIST") > -1) {
			return null;
		}
		str = str.replace("**ELECTRONIC TICKET PNR**", "");
		return split(str, "\r");
	}

	private static void getTKT(RtResult result, String str) {
		if (str.indexOf("SSR TKNE") > -1) {
			PNRTicket tktEntity = null;
			String patt = "-\\d{1,3}\\.";
			Pattern p = Pattern.compile(patt);
			Matcher m = p.matcher(str);
			if (m.find()) {
				String temp[] = split(str, patt);
				for (String it : temp) {
					tktEntity = buildTktEntity(result, it);
					result.getTicketList().add(tktEntity);
				}
			} else {
				tktEntity = buildTktEntity(result, str);
				result.getTicketList().add(tktEntity);
			}
		}
	}

	private static PNRTicket buildTktEntity(RtResult result, String string) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		String year = format.format(new Date());;
		
		int passindex;
		String arrays[] = split(string, " ");
		// 11.SSR TKNE 3U HK1 PEKCTU 8882 Y28SEP 8762542067824/1/P2
		PNRTicket tktEntity = new PNRTicket();
		tktEntity.setCarrier(arrays[2]);
		tktEntity.setOrg(arrays[4].substring(0, 3));
		tktEntity.setDst(arrays[4].substring(3));
		
		tktEntity.setFlightDate(arrays[6].substring(1));
		

		if(tktEntity.getFlightDate().length()<=6){
			tktEntity.setFlightDate(tktEntity.getFlightDate()+year);
		}
		tktEntity.setFlightDate(DateUtil.ymd(tktEntity.getFlightDate()));
		
		tktEntity.setCabin(arrays[6].substring(0,1));
		tktEntity.setFlightNo(arrays[5]);
		tktEntity.setTicketNo(arrays[7].substring(0, 13));
		int indexofp = arrays[7].indexOf("P");
		if (indexofp == -1) {
			passindex = 1;
		} else {
			passindex = Integer.parseInt(arrays[7].substring(indexofp + 1));
		}
		PNRPasseenger passeenger = result.getPasseengerList()
				.get(passindex - 1);
		tktEntity.setPassId(passeenger.getIdNo());
		tktEntity.setPassName(passeenger.getName());
		return tktEntity;
	}

	private static void getFOID4Passenger(RtResult result, String str) {
		if (str.indexOf("SSR FOID") > -1) {
			String[] arrays = split(str, " ");
			arrays = split(arrays[arrays.length - 1], "/");
			int passIndex = -1;
			if (arrays.length == 1) {
				passIndex = 1;
			} else {
				passIndex = Integer.parseInt(arrays[1].substring(1));
			}
			PNRPasseenger pass = result.getPasseengerList().get(passIndex - 1);
			pass.setIdType(arrays[0].substring(0, 2));
			pass.setIdNo(arrays[0].substring(2));
		}
	}

	private static void getPassenger(RtResult rtResult, String[] passItems,
			int pnrIndex) {
		PNRPasseenger passeenger;
		if(!rtResult.isGroup()){
			for (int i = 0; i < pnrIndex; i++) {
				String[] arrays = split(passItems[i], " ");
				for (String temp : arrays) {
					if(temp.toUpperCase().indexOf(rtResult.getPnrCode().toUpperCase())>-1)
						continue;
					passeenger = new PNRPasseenger();
					buildPassenger(passeenger, temp);
					rtResult.getPasseengerList().add(passeenger);
				}
			}
			rtResult.setPassengerNumber(rtResult.getPasseengerList().size());
		}else{//is group
			for(int j=1;j<passItems.length;j++){
				String[] arrays = split(passItems[j], "\\d{1,2}\\.");
				for( String temp : arrays){
					passeenger = new PNRPasseenger();
					buildPassenger(passeenger, temp);
					rtResult.getPasseengerList().add(passeenger);
				}
				if(rtResult.getPassengerNumber()==rtResult.getPasseengerList().size())
					break;
			}
		}
	}

	private static void buildPassenger(PNRPasseenger passeenger, String temp) {
		temp = temp.replaceAll("\\d{1,2}\\.", "");
		if (temp.toUpperCase().endsWith("CHD")) {
			passeenger.setType(PNRPasseenger.PASSENGER_TYPE_CHILD);
			passeenger.setName(temp.replace("CHD", ""));
		} else {
			passeenger.setType(PNRPasseenger.PASSENGER_TYPE_ADULT);
			passeenger.setName(temp);
		}
	}

	public static void main(String[] args) {
		String dd = "1.何凡  ";
		String[] gg = split(dd, "\\d{1,2}\\.");
		ArrayUtils.toString(gg);

		String result = "   **ELECTRONIC TICKET PNR** \n 1.部星辰 2.孙林光 JNMRKG   \n 3.  3U8882 Y   FR28SEP  PEKCTU RR2   1120 1415          E T3T1 \n 4.  3U8885 H   FR05OCT  CTUPEK RR2   1130 1410          E T1T3 \n 5.BJS/T BJS/T 010-62252769/PEK XIN LONG AVATION TICKET AGENCY CO.,LTD/WANG \n     WEI ABCDEFG\n 6.PEK-56188836 \n 7.T\n 8.SSR FOID 3U HK1 NI130283199108035654/P2  \n 9.SSR FOID 3U HK1 NI110107199201133114/P1  \n10.SSR ADTK 1E BY BJS21SEP12/1120 OR CXL 3U8882 Y28SEP  \n11.SSR TKNE 3U HK1 PEKCTU 8882 Y28SEP 8762542067824/1/P2                       +\n12.SSR TKNE 3U HK1 PEKCTU 8882 Y28SEP 8762542067823/1/P1                       -13.SSR TKNE 3U HK1 CTUPEK 8885 H05OCT 8762542067823/2/P1\n14.SSR TKNE 3U HK1 CTUPEK 8885 H05OCT 8762542067824/2/P2\n15.OSI 3U CTCT 13699187500  \n16.RMK CA/NJVHS6\n17.RMK TJ AUTH BJS272   \n18.RMK TJ AUTH BJS584   \n19.RMK AUTOMATIC FARE QUOTE \n20.FN/A/FCNY2520.00/SCNY2520.00/C3.00/XCNY360.00/TCNY100.00CN/TCNY260.00YQ/ \n    ACNY2880.00 \n21.TN/876-2542067823/P1 \n22.TN/876-2542067824/P2                                                        +\n23.FP/CASH,CNY                                                                 -24.BJS621   \n\n";
		result=" 0.2CTRIP/GRP NM2 HSF651\n 1.何凡 2.WAN/DIAN DIAN \n 3.  3U8569 M   TU02OCT  CTUSYX RR2   2005 2225          E T1-- \n 4.  3U8570 M   SA06OCT  SYXCTU RR2   2315 0140+1        E --T1 \n 5.SHA/T SHA/T-021-34064880X54133/SHA HUACHENG SOUTHWEST TRAVEL/SHAO JI HONG\n     ABCDEFG\n 6.13880402883/DJ   \n 7.TL/1700/01OCT/SHA717 \n 8.SSR FOID 3U HK1 NIG35264105/P2   \n 9.SSR FOID 3U HK1 NI510105198501061017/P1  \n10.SSR FQTV 3U HK1 CTUSYX 8569 M02OCT 3U970504824/C/P1  \n11.SSR FQTV 3U HK1 SYXCTU 8570 M06OCT 3U970504824/C/P1                         +\n12.RMK CA/NTXFN8                                                               -13.SHA717   \n\n";
		System.out.println(result);
		RtResult ffff =  parseRt(result, "NWQRVS");
		System.out.println(ffff);
	}

	public static String[] split(String string, String operator) {
		if (string == null) {
			return null;
		}
		String[] temp = string.split(operator);
		String[] result = new String[temp.length];
		int i = 0;
		for (String tt : temp) {
			if (tt == null || tt.equals("") || tt.trim().equals(""))
				continue;
			result[i++] = tt;
		}
		return Arrays.copyOf(result, i);
	}
}
